<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAdd">新增菜单</el-button>
        </div>
      </template>
      <el-tree
        :data="treeData"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span>
              <el-tag size="small" v-if="data.type === 1">目录</el-tag>
              <el-tag size="small" type="success" v-else-if="data.type === 2">菜单</el-tag>
              <el-tag size="small" type="info" v-else>按钮</el-tag>
              <el-button
                type="text"
                size="small"
                @click="() => append(data)"
              >
                添加
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="() => edit(node, data)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="() => remove(node, data)"
              >
                删除
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

interface Tree {
  id: number
  label: string
  type: number // 1:目录 2:菜单 3:按钮
  children?: Tree[]
}

const id = ref(4)

const treeData = ref<Tree[]>([
  {
    id: 1,
    label: '系统管理',
    type: 1,
    children: [
      {
        id: 2,
        label: '用户管理',
        type: 2
      },
      {
        id: 3,
        label: '角色管理',
        type: 2
      }
    ]
  }
])

const append = (data: Tree) => {
  const newChild = { id: id.value++, label: '新菜单', type: 2 }
  if (!data.children) {
    data.children = []
  }
  data.children.push(newChild)
}

const edit = (node: any, data: Tree) => {
  console.log('Edit', node, data)
}

const remove = (node: any, data: Tree) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d: Tree) => d.id === data.id)
  children.splice(index, 1)
}

const handleAdd = () => {
  treeData.value.push({
    id: id.value++,
    label: '新目录',
    type: 1
  })
}
</script>

<style scoped>
.permission-container {
  padding: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}
</style>
